import json , os , uuid
import traceback
import librosa

from utils.loggingConfig import get_logger
from fastapi import APIRouter , Request , File, UploadFile
from fastapi.responses import StreamingResponse
from service.wav2vec2Service import wav2vecService

fapp = None
router = APIRouter()

root_path = os.path.abspath(__file__)
for i in range(2):
    root_path = os.path.dirname(root_path)

UPLOAD_DIR = os.path.join(root_path , "uploads")
if os.path.exists(UPLOAD_DIR) == False:
    os.makedirs(UPLOAD_DIR)

logger = get_logger('')

# 支持的音频格式
ALLOWED_EXTENSIONS =  {".wav", ".mp3", ".flac", ".ogg", ".m4a"}

def init():
    global ALLOWED_EXTENSIONS
    ALLOWED_EXTENSIONS = os.getenv('ALLOWED_EXTENSIONS' )
    if ALLOWED_EXTENSIONS :
        ALLOWED_EXTENSIONS = set(ALLOWED_EXTENSIONS.replace(" ","").split(","))
    else:
        ALLOWED_EXTENSIONS = {".wav", ".mp3", ".flac", ".ogg", ".m4a"}


init()


@router.post("/wav2vec2", description="体验 wav2vec2 模型，语音转向量，情感分类")
async def wav2vec2( file: UploadFile = File(...)):
    logger.info("######### wav2vec2")
    req_id = uuid.uuid1()

    # 检查文件扩展名
    print(f"########### file {file}")
    print(f"########### ALLOWED_EXTENSIONS {ALLOWED_EXTENSIONS}")

    file_ext = file.filename.lower()
    if file_ext not in ALLOWED_EXTENSIONS:
        # 保存文件
        filename = f'upload-{req_id}-{file.filename}'
        filepath = os.path.join(root_path , f'{UPLOAD_DIR}/{filename}' )
        try:
            with open(filepath, "wb") as f:
                content = await file.read()
                f.write(content)

            vector , classmap = await wav2vecService(filepath , 16000)

            return {"success": True, "code": 200, 'vector': vector , 'emotionClass':classmap}
        except Exception as e:
            error_msg = traceback.format_exc()
            logger.error(f"req_id:{req_id} error_msg:{error_msg}")
            return {"success":False , "code":500 , "error_msg":f"文件上传失败: {error_msg}"}
        finally:
            if os.path.exists(filepath) :
                os.remove(filepath)